Excersies

Here follows some excersies to practise the basic python syntax.

Excersice 1

Write a functions that reverses a string. So if the input is "function" the output should be "noitcunf".

It is possible to loop through the characters in a string in a standard for loop and the len() function will return the length of the string.


In [ ]:
def reverse_string(string):
    """Reverses the string"""
    result = ""
    # your code goes here

    return result


if "noitcunf" == reverse_string("function"):
    print("Excersice solved (at least for this input. You should check you function works for other values too)")
else:
    print("Not working")

Excersice 2

Reading data from a csv file and calculating the average value of BMI

The structure of the file is

height, weight 1.8, 43

To read a file in python we can use the open() function and it is normal to di it like this:

with open(filename) as f:
   read_file

The file object has multiple way of reading the content. Either f.read(), this will return the whole file content or it is possible to loop through all the lines in the file as this:

with open(filename) as f:
   for line in f:
       print(line)

The file is in the same folder as this notebook and is called bmi.csv

If you have a string "a,b" you can use the split function to split on a delimiter. So

"a,b".split(",") == ["a", "b"]

To perform and computations on the numbers reember to cast the to a numerical type using ( float() or int())


In [ ]:
# Your code goes here

In [ ]:
# Bonus code to create the csv file we used in the excersice above

import random
with open("bmi.csv", "w") as f:
    f.write("height,weight")
    for i in range(100):
        f.write(str(1 + random.random()) + "," + str(random.randint(50, 120)) + "\n")

Exersice 3

Write a function that takes a list of python dictionaries in to an html table. (Html table specification: https://www.tutorialspoint.com/html/html_tables.htm). The table should include headers which corresponds to the keys in the dictionary. We also pass a list of the headers in the correct order to the function. We can assume that all the kesy in the header is in each dictionary. (As an extension you can try to extend the code to deal with non-existent keys)

The result should look something like this:

a b
1 2
3 4


In [ ]:
# To see if the result is working you can use the following code: 

from IPython.core.display import display, HTML

# This is the sort of string we want to produce
string = "<table> <tr> <th> a </th> <th> b </th> </tr><tr> <td> 1 </td> <td> 2 </td> </tr> <tr> <td> 3 </td> <td> 4 </td></tr> </table>"

display(HTML(string)) # Displays the html

Your code will go in the html_table function. If you have an idea of how to write the whole function, just do that. Otherwise you can use the following steps to help you get there.

Note that since a dictionary is unorder you can use any order of the he

  1. Make the function return an empty table ( < table> < /table>")
  2. Each row in the table (including the header) needs to be inside tr-tags (< tr> Row in here < /tr>)
  3. Header elements needs the (< th> Header < /th>) tag.
  4. The main part of the table requires a double loop through the values of the dictionaries in the list.

In [ ]:
def html_table(header, lists):
    table = ""
    # Your code in here
    
    return table


lists = [{"a": 1, "b": 2}, {"a":3, "b": 4}]

table = html_table(["a", "b"],lists)

display(HTML(table))

Excersice 4

Retreiving data from the web using the requests library (http://docs.python-requests.org/en/master/).

If importing requests does not work try to install it with :

!pip install requests

We will start with the requests.get function. Read the documentation here and http://docs.python-requests.org/en/master/user/quickstart/ and try to write some simple code that prints as a string the content of google.com


In [ ]:
import requests

# your code goes here

We now want to get some data from the jordan public health surveillance system. Most of the data is password protected, but we can access some of the very basic data at http://iers.moh.gov.jo/api/key_indicators.

You can see what the data looks like by click opening the link in your browser. The data is structured as follows: under the key reg_2 we find the total number of consultations and under tot_1 we find the total number of cases submitted to the system. The weeks give the number per epi_week and total gives the total.

The data is in the JSON format, this means that we need to load it to a dictionary before we can access it. Ther are multiple ways of doing that, but the requests library can do it for us see here(http://docs.python-requests.org/en/master/user/quickstart/#json-response-content).

Write some code that can print out the total number of consultations and cases this year using the data from the iers site.


In [ ]:

As a last part of this excersie we want to try to present the above data as a graph. Python has many plotting libraries, but we will use matplotlib, see here: http://matplotlib.org/users/pyplot_tutorial.html

install this package with :

!conda install matplotlib

To start with follow the tutorial to create the first straight line graph. To get the charts to show up well in the notebook run the cell below.


In [ ]:
import matplotlib
%matplotlib notebook

In [ ]:
# Your code to generate a simple straight line chart here.

We now want to try to plot the number of cases per week using matplotlib. First you need to create two lists. One with the week-numbers in ascending order and one with the counts from the data we got above ( needs to be in the same order). The sorted() function in python can be used if needed( https://docs.python.org/3.6/howto/sorting.html#sortinghowto)

Then try to follow the tutorial to create first a line plot of the data.

The change it to show dots where the data is instead of a continues line. Following the same tutorial you can also learn how to add titles to axis and to the plot and how to style the plot in different ways.

It is also possible to create a bar chart. Trying looking via google for "matplotlib barchart" to find some reference you can use. Or you can search for bar charts on the matplotlib website: http://matplotlib.org/search.html?q=bar


In [ ]:


In [ ]:

More excersies:

For many more simple excersies you can try this: http://www.ling.gu.se/~lager/python_exercises.html


In [ ]: